package com.base.api.thbi.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.api.thbi.InsuranceService;
import com.base.dao.thbi.InsuranceVsPriceSychiMapper;
import com.base.dao.thbi.MipsCatalogDownloadRecordMapper;
import com.base.utils.*;
import com.base.vo.thbi.InsuranceVsPriceSychi;
import com.base.vo.thbi.MipsCatalogDownloadRecord;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class InsuranceServiceImpl implements InsuranceService {
    @Autowired
    private InsuranceVsPriceSychiMapper insuranceVsPriceSychiMapper;
    @Autowired
    private MipsCatalogDownloadRecordMapper mipsCatalogDownloadRecordMapper;
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public String updateInsuranceSychi(String yblx, String startDate) {
        Map<String, Object> map = new HashMap<>();
        String jysrParams = assemblyPara("06", startDate, yblx);

        long start;
        long end;
        JSONObject jsonObject;
        try {
            start = System.currentTimeMillis();
            msg(jysrParams);
            msg("正在调用医保接口,等待返回交易结果,请稍后...");
            String result = HttpRequsetUtil.doPost(jysrParams);
            end = System.currentTimeMillis();
            msg("调用完成,用时:".concat(String.valueOf(end - start)).concat("ms"));
            jsonObject = JSON.parseObject(result).getJSONObject("args");
        } catch (Exception e) {
            map.put("count", 0);
            map.put("data", new ArrayList<>());
            map.put("code", 100);
            map.put("msg", "后台调用医保接口失败," + e.toString());
            return JSON.toJSONString(map);
        }
        List<InsuranceVsPriceSychi> list = new ArrayList<>();
        JSONArray resultSet = jsonObject.getJSONArray("resultSet");
        for (int i = 0; i < resultSet.size(); i++) {
            JSONObject jo = resultSet.getJSONObject(i);
            String jyscMsg = jo.getString("jyscMsg");
            if (jyscMsg == null) {
                jyscMsg = jo.getString("JyscXml");
            }
            msg("开始解析...");
            start = System.currentTimeMillis();
            String[] rows = jyscMsg.split("\n");
            if (rows.length > 1) {
                for (String column : rows) {
                    String[] columns = column.split("\t");
                    InsuranceVsPriceSychi itr = new InsuranceVsPriceSychi();
                    if (columns.length > 6) {
                        itr.setAka402(columns[0]);
                        itr.setAka403(columns[1]);
                        itr.setAkb020(columns[2]);
                        itr.setAka400(columns[3]);
                        itr.setAkc224(columns[4]);
                        itr.setAkc401(columns[5]);
                        itr.setAka404(columns[6]);
                        itr.setAka405(columns[7]);
                        itr.setAka070(columns[8]);
                        itr.setAka071(columns[9]);
                        itr.setAka072(columns[10]);
                        itr.setAka406(columns[11]);
                        itr.setAka076(columns[12]);
                        itr.setAka616(columns[13]);
                        itr.setAka084(columns[14]);
                        itr.setAka081(columns[15]);
                        itr.setAka082(columns[16]);
                        itr.setAkc175(columns[17]);
                        itr.setAae011(columns[18]);
                        itr.setAae036(columns[19]);
                        itr.setAae013(columns[20]);
                        itr.setAka077(columns[21]);
                        itr.setAae034(columns[22]);
                    } else {
                        itr.setAka402(columns[0]);
                        itr.setAka403(columns[1]);
                        itr.setAkb020("42030002");
                        itr.setAka400(columns[2]);
                        itr.setAkc401(columns[3]);
                        itr.setAkc175(columns[4]);
                        itr.setAkc224("All");
                    }
                    list.add(itr);
                }
                // insuranceVsPriceSychiMapper.deleteAll();
            }
            end = System.currentTimeMillis();
            msg("解析完成,用时:".concat(String.valueOf(end - start)).concat("ms"));
        }
        int i = 0;
        int j = 0;

        //清空临时表
        insuranceVsPriceSychiMapper.exceTruncate();

        List<InsuranceVsPriceSychi> list1 = new ArrayList<>();

        msg("开始批量插入...");
        start = System.currentTimeMillis();
        if (list.size() > 0) {
            msg("本次下载到的记录数：" + list.size() + "条...");
            List<List<InsuranceVsPriceSychi>> list2 = splitList(list, 400);
            for (List<InsuranceVsPriceSychi> list3 : list2) {
//                for (InsuranceVsPriceSychi sychi : list3) {
//                    i += insuranceVsPriceSychiMapper.insert(sychi);
//                    msg("已插入成功" + i + "条...");
//                }
                i += insuranceVsPriceSychiMapper.insertBatch(list3);
                msg("正在处理第: " + i + "/" + list.size() + " 条...");
            }
        }
        end = System.currentTimeMillis();
        msg("处理完成,用时: ".concat(String.valueOf(end - start)).concat("ms"));

        start = System.currentTimeMillis();
        msg("开始删除...");

        j = insuranceVsPriceSychiMapper.exceDeleteCount();
        insuranceVsPriceSychiMapper.exceDelete();

        end = System.currentTimeMillis();
        msg("删除完成,用时: ".concat(String.valueOf(end - start)).concat("ms"));

        msg("开始新增数据...");
        start = System.currentTimeMillis();
        i = insuranceVsPriceSychiMapper.exceInsertCount();
        insuranceVsPriceSychiMapper.exceInsert();

//        List<List<InsuranceVsPriceSychi>> allList = getinsertList(list, insuranceVsPriceSychiList);
//        List<InsuranceVsPriceSychi> insertList = allList.get(0);
//        List<InsuranceVsPriceSychi> updateList = allList.get(1);
        end = System.currentTimeMillis();
        msg("新增完成,用时: ".concat(String.valueOf(end - start)).concat("ms"));
//        msg("开始批量插入...");
//        start = System.currentTimeMillis();
//        if (insertList.size() > 0) {
//            msg("合计" + insertList.size() + "条...");
//            List<List<InsuranceVsPriceSychi>> list2 = splitList(insertList, 200);
//            for (List<InsuranceVsPriceSychi> list3 : list2) {
////                for (InsuranceVsPriceSychi sychi : list3) {
////                    i += insuranceVsPriceSychiMapper.insert(sychi);
////                    msg("已插入成功" + i + "条...");
////                }
//                i += insuranceVsPriceSychiMapper.insertBatch(list3);
//                msg("已插入成功" + i + "/" + insertList.size() + "条...");
//            }
//        }
//        end = System.currentTimeMillis();
//        msg("批量插入完成,用时:".concat(String.valueOf(end - start)).concat("ms"));
//
//        msg("开始更新,共"+Integer.toString(updateList.size())+"条...");
//        start = System.currentTimeMillis();
//        if (updateList.size() > 0) {
////            List<List<InsuranceVsPriceSychi>> list2 = splitList(updateList, 50);
////            for (List<InsuranceVsPriceSychi> list3 : list2) {
////                j += insuranceVsPriceSychiMapper.updateBatch(list3);
////            }
//            for(InsuranceVsPriceSychi list2 :updateList){
//                j +=  insuranceVsPriceSychiMapper.updateByPrimaryKey(list2);
//            }
//        }
//
//        end = System.currentTimeMillis();
//        msg("更新完成,用时:".concat(String.valueOf(end - start)).concat("ms"));
        map.put("count", 0);
        map.put("data", list1);
        map.put("code", 0);
        String msg = "下载:" + String.valueOf(list.size()) + "条,新增:" + String.valueOf(i - j) + "条,更新:" + j + "条";
        map.put("msg", msg);
        MipsCatalogDownloadRecord mipsCatalogDownloadRecord = new MipsCatalogDownloadRecord();
        mipsCatalogDownloadRecord.setInsuranceSystemId(Long.parseLong(yblx));
        mipsCatalogDownloadRecord.setNote(msg);
        mipsCatalogDownloadRecord.setOperateTime(Date.valueOf(startDate));
        mipsCatalogDownloadRecordMapper.insert(mipsCatalogDownloadRecord);
        return JSON.toJSONString(map);
    }


    public List<List<InsuranceVsPriceSychi>> splitList(List<InsuranceVsPriceSychi> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }
        List<List<InsuranceVsPriceSychi>> result = new ArrayList<List<InsuranceVsPriceSychi>>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<InsuranceVsPriceSychi> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }

    public List<List<InsuranceVsPriceSychi>> getinsertList(List<InsuranceVsPriceSychi> list1, List<InsuranceVsPriceSychi> list2) {
        List<InsuranceVsPriceSychi> list3;
        List<InsuranceVsPriceSychi> list4;
        List<List<InsuranceVsPriceSychi>> result;
        if (list1.size() == 0 && list1 == null) {
            return null;
        } else {
            list3 = new ArrayList<>();
            list4 = new ArrayList<>();
            result = new ArrayList<>();
            Map<String, Integer> map = new HashMap<>();
            Map<String, InsuranceVsPriceSychi> map2 = new HashMap<>();

            for (InsuranceVsPriceSychi ivps : list1) {
                map.put(ivps.getAkb020() + "-" + ivps.getAka400() + "-" + ivps.getAkc224(), 1);
                map2.put(ivps.getAkb020() + "-" + ivps.getAka400() + "-" + ivps.getAkc224(), ivps);
            }
            for (InsuranceVsPriceSychi ms : list2) {
                if (map.get(ms.getAkb020() + "-" + ms.getAka400() + "-" + ms.getAkc224()) != null) {
                    map.put(ms.getAkb020() + "-" + ms.getAka400() + "-" + ms.getAkc224(), 100);

                    InsuranceVsPriceSychi ivps = map2.get(ms.getAkb020() + "-" + ms.getAka400() + "-" + ms.getAkc224());

                    if (!ClassCompareUtil.compareObject(ms, ivps)) {
                        list4.add(ivps);
                    }
                }
            }
            for (InsuranceVsPriceSychi ivps : list1) {

                if (map.get(ivps.getAkb020() + "-" + ivps.getAka400() + "-" + ivps.getAkc224()) == 1) {
                    list3.add(ivps);
                }

            }
            result.add(list3);
            result.add(list4);
        }
        return result;
    }

    @Override
    public String findAll(String yblx, String itemCode, String itemName, String pageNum, String pageSize, String order, String sort) {
        if (pageNum == null) {
            pageNum = "1";
        }
        if (pageSize == null) {
            pageSize = "50";
        }
        if (order == null) {
            order = "AAE034";
        }
        if (sort == null) {
            sort = "desc";
        }

        int pageNum1 = Integer.parseInt(pageNum);
        int pageSize1 = Integer.parseInt(pageSize);
        int pageNumStart = (pageNum1 - 1) * pageSize1;
        int pageNumEnd = pageNum1 * pageSize1 - 1;
        String qybm = insuranceVsPriceSychiMapper.queryAreaCode(yblx);
        if ("".equals(qybm) || qybm == null) {
            qybm = yblx;
        }
        PageHelper.startPage(pageNum1,pageSize1);
        //int count = insuranceVsPriceSychiMapper.selectCount(qybm, itemCode, itemName);
        List<InsuranceVsPriceSychi> list = insuranceVsPriceSychiMapper.selectByCodeOrName(qybm, itemCode, itemName, order, sort);
        PageInfo<InsuranceVsPriceSychi> pageInfo = new PageInfo<>(list);
        Map<String, Object> map = new HashMap<>();
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        map.put("code", 0);
        map.put("msg", "");
        return JSON.toJSONString(map);
    }

    @Override
    public String findUpdateLog(String yblx) {
        try {
            MipsCatalogDownloadRecord mipsCatalogDownloadRecord = mipsCatalogDownloadRecordMapper.selectByYblx(yblx);
            return ResultUtil.success(mipsCatalogDownloadRecord);
        } catch (Exception e) {
            return ResultUtil.error(e.getLocalizedMessage());
        }

    }

    public String assemblyPara(String startDate, String endDate, String yblx) {
        String jybh = "";
        String jysr = "";
        String qybm = "";
        String action = "";
        String commandSet = "";
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        if ("42030002".equals(yblx)) {
            action = "SYPMEDICARE_CALL";
            jybh = "82";
            jysr += "<?xml version='1.0' encoding='GBK' standalone='yes' ?>";
            jysr += "<input>";
            jysr += "<ake005></ake005>";
            jysr += "<outputfile>D:\\\\sjm\\\\downLoadInsuranceVsPrice.txt</outputfile>";
            jysr += "</input>";
            commandSet = "\"Jybh\":\"" + jybh + "\",\"JysrXml\":\"" + jysr + "\"";
        } else {
            action = "SY_JINBAO_CALL";
            jybh = "1300";
            qybm = insuranceVsPriceSychiMapper.queryAreaCode(yblx);
            jysr = jybh + "^" + qybm + "^10882^^" + System.currentTimeMillis() + "^0000^" + startDate.replaceAll("-", "") + "|" + endDate.replaceAll("-", "") + "|^";
            commandSet = "\"areaCode\":\"" + qybm + "\",\"jybh\":\"1100\",\"jysrParam\":\"" + jysr + "\"";
        }
        String result = "{\"action\":\"" + action + "\",\"args\":{\"params\":{\"filePath\": \"\"},\"commandSet\":[{" + commandSet + "}]}}";
        return result;
    }

    public void msg(String msg) {
        logger.info(msg);
        WebSocketServer.sendInfo(msg, ThreadLocalUtil.getSessionId());
    }
}
